package com.alienlab.finder.service.impl;

import com.alienlab.finder.domain.AppUser;
import com.alienlab.finder.domain.CheckTask;
import com.alienlab.finder.domain.Warning;
import com.alienlab.finder.repository.AppUserRepository;
import com.alienlab.finder.repository.CheckTaskRepository;
import com.alienlab.finder.repository.RelationshipRepository;;
import com.alienlab.finder.service.TaskDetailsService;
import com.alienlab.finder.domain.TaskDetails;
import com.alienlab.finder.repository.TaskDetailsRepository;
import com.alienlab.finder.service.WarningService;
import com.alienlab.finder.service.dto.globalData;
import com.alienlab.finder.service.util.DistanceUtil;
import com.alienlab.finder.web.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.*;

/**
 * Service Implementation for managing TaskDetails.
 */
@Service
@Transactional
public class TaskDetailsServiceImpl implements TaskDetailsService {

    private final Logger log = LoggerFactory.getLogger(TaskDetailsServiceImpl.class);

    private final TaskDetailsRepository taskDetailsRepository;
    private final CheckTaskRepository checkTaskRepository;
    private final RelationshipRepository relationshipRepository;
    private final WarningService warningService;
    private final AppUserRepository appUserRepository;
    private static Map<Long,CheckTask> checkTaskMap = new HashMap<>();

    public TaskDetailsServiceImpl(AppUserRepository appUserRepository,WarningService warningService,RelationshipRepository relationshipRepository,CheckTaskRepository checkTaskRepository,TaskDetailsRepository taskDetailsRepository) {
        this.taskDetailsRepository = taskDetailsRepository;
        this.checkTaskRepository = checkTaskRepository;
        this.relationshipRepository = relationshipRepository;
        this.warningService =warningService;
        this.appUserRepository = appUserRepository;
    }

    /**
     * Save a taskDetails.
     *
     * @param taskDetails the entity to save
     * @return the persisted entity
     */
    @Override
    public TaskDetails save(TaskDetails taskDetails) {
        log.debug("Request to save TaskDetails : {}", taskDetails);
        return taskDetailsRepository.save(taskDetails);
    }

    /**
     * Get all the taskDetails.
     *
     * @param pageable the pagination information
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public Page<TaskDetails> findAll(Pageable pageable) {
        log.debug("Request to get all TaskDetails");
        return taskDetailsRepository.findAll(pageable);
    }


    /**
     * Get one taskDetails by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<TaskDetails> findOne(Long id) {
        log.debug("Request to get TaskDetails : {}", id);
        return taskDetailsRepository.findById(id);
    }

    /**
     * Delete the taskDetails by id.
     *
     * @param id the id of the entity
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete TaskDetails : {}", id);
        taskDetailsRepository.deleteById(id);
    }

    @Override
    public Warning addPositionInfomation(Long task_id, String position_x, String position_y) throws Exception {
        int count = 0;
        CheckTask checkTask = new CheckTask();
        if (checkTaskMap.isEmpty()){
            checkTask = checkTaskRepository.findById(task_id).orElse(null);
            if (checkTask==null){
                throw new Exception("未查到到task_id为："+task_id+"的监控任务,不可增加监控位置信息");
            }else {
                checkTaskMap.put(task_id,checkTask);

            }
        }
        CheckTask checkTask1 = checkTaskMap.get(task_id);
        if (checkTask1!=null){
            count++;
            checkTask = checkTask1;
        }

        if (count==0){
            checkTask = checkTaskRepository.findById(task_id).orElse(null);
            if (checkTask==null){
                throw new Exception("未查到到task_id为："+task_id+"的监控任务,不可增加监控位置信息");
            }else {
                checkTaskMap.put(task_id,checkTask);
            }
        }

        TaskDetails taskDetails = new TaskDetails();
        taskDetails.setTaskId(task_id);
        taskDetails.setPositionX(position_x);
        taskDetails.setPositionY(position_y);
        taskDetails.setTime(ZonedDateTime.now());
        taskDetails = taskDetailsRepository.save(taskDetails);

        String distacne = checkTask.getDistance();
        String origin_x = checkTask.getOrigin_x();
        String origin_y = checkTask.getOrigin_y();


        String current_instance = DistanceUtil.algorithm(Double.valueOf(position_x),Double.valueOf(position_y),Double.valueOf(origin_x),Double.valueOf(origin_y));
        log.debug("当前距离为："+current_instance);
        if ("".equals(distacne) || distacne==null){
            distacne = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(checkTask.getAdminOpenId(),checkTask.getGuestOpenId()).getDistanceSize();
        }
        log.debug("安全距离为："+distacne);
        Warning warning = new Warning();
        double this_distance = Double.valueOf(current_instance) - Double.valueOf(distacne);
        log.debug("超出的距离为："+this_distance);
        if (this_distance>0){
             warning = warningService.addWarning(checkTask.getAdminOpenId(),checkTask.getGuestOpenId(),"被监控人超出安全区域"+this_distance+"米");
             checkTask.setWarningId(warning.getId());
             checkTask = checkTaskRepository.save(checkTask);
             //更新map
            checkTaskMap.put(task_id,checkTask);
            String name = "";
             AppUser appUser = appUserRepository.findByOpenId(checkTask.getGuestOpenId());
             if (appUser!=null && appUser.getName()!=null && !"".equals(appUser.getName())){
                 name = appUser.getName();
             }
//             System.out.println(globalData.websocketmap.toString());
//            System.out.println(checkTask.getAdminOpenId());
//            System.out.println(checkTask.getGuestOpenId());
//            System.out.println(globalData.websocketmap.get(checkTask.getGuestOpenId()));
             WebSocketServer.SendMessage(globalData.websocketmap.get(checkTask.getAdminOpenId().toLowerCase()),checkTask.getId()+";"+name+"已超出安全区域"+this_distance+"米");
             WebSocketServer.SendMessage(globalData.websocketmap.get(checkTask.getGuestOpenId().toLowerCase()),"您已超出安全范围:"+this_distance+"米");

        }

        return warning;
    }

    @Override
    public List<TaskDetails> getRoutes(Long task_id) throws Exception {
        CheckTask checkTask = checkTaskRepository.findById(task_id).orElse(null);
        if (checkTask==null){
            throw new Exception("未查到到task_id为:"+task_id+"的任务信息");
        }
        List<TaskDetails> taskDetailsList =taskDetailsRepository.findByTaskIdOrderByTimeAsc(task_id);

        return taskDetailsList;
    }
}
